package net.mingsoft.expertmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.expertmanage.entity.CompanyEntity;
import net.mingsoft.expertmanage.service.ICompanyService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 企业管理控制器
 */
@Api(value = "企业管理接口")
@RestController
@RequestMapping("/${ms.manager.path}/expertmanage/company")
public class CompanyController {

    private static final Logger LOG = LoggerFactory.getLogger(CompanyController.class);

    @Autowired
    private ICompanyService companyService;

    /**
     * 查询企业列表
     */
    @ApiOperation(value = "查询企业列表")
    @GetMapping("/list")
    public ResultData list(@RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
                            @RequestParam(value = "keyword", required = false) String keyword) {
        Page<CompanyEntity> page = new Page<>(pageNum, pageSize);
        QueryWrapper<CompanyEntity> queryWrapper = new QueryWrapper<>();
        
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("company_name", keyword).or()
                      .like("company_code", keyword).or()
                      .like("business_keywords", keyword);
        }
        
        return ResultData.build().success(companyService.page(page, queryWrapper));
    }

    /**
     * 保存企业
     */
    @ApiOperation(value = "保存企业")
    @PostMapping("/save")
    public ResultData save(@RequestBody CompanyEntity company) {
        companyService.save(company);
        return ResultData.build().success();
    }

    /**
     * 更新企业
     */
    @ApiOperation(value = "更新企业")
    @PostMapping("/update")
    public ResultData update(CompanyEntity company) {
        companyService.updateById(company);
        return ResultData.build().success();
    }

    /**
     * 删除企业
     */
    @ApiOperation(value = "删除企业")
    @PostMapping("/delete/{companyCode}")
    public ResultData delete(@PathVariable("companyCode") String companyCode) {
        try {
            if (StringUtils.isEmpty(companyCode)) {
                return ResultData.build().error("企业编号不能为空");
            }
            
            // 查找企业确认存在
            QueryWrapper<CompanyEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("company_code", companyCode);
            CompanyEntity company = companyService.getOne(queryWrapper);
            
            if (company == null) {
                return ResultData.build().error("未找到对应企业信息");
            }
            
            boolean result = companyService.remove(queryWrapper);
            if (result) {
                LOG.info("成功删除企业: {}", companyCode);
                return ResultData.build().success("企业删除成功");
            } else {
                return ResultData.build().error("删除失败");
            }
        } catch (Exception e) {
            LOG.error("删除企业时发生错误: " + e.getMessage(), e);
            return ResultData.build().error("删除企业时发生错误: " + e.getMessage());
        }
    }

    /**
     * 批量删除企业
     */
    @ApiOperation(value = "批量删除企业")
    @PostMapping("/delete")
    public ResultData delete(@RequestBody List<String> companyCodes) {
        try {
            if (companyCodes == null || companyCodes.isEmpty()) {
                return ResultData.build().error("企业编号列表不能为空");
            }
            
            QueryWrapper<CompanyEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("company_code", companyCodes);
            boolean result = companyService.remove(queryWrapper);
            
            if (result) {
                LOG.info("成功批量删除{}个企业", companyCodes.size());
                return ResultData.build().success("批量删除成功");
            } else {
                return ResultData.build().error("批量删除失败");
            }
        } catch (Exception e) {
            LOG.error("批量删除企业时发生错误: " + e.getMessage(), e);
            return ResultData.build().error("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有企业（不分页）
     */
    @ApiOperation(value = "获取所有企业")
    @GetMapping("/all")
    public ResultData getAll() {
        return ResultData.build().success(companyService.list());
    }
    
    /**
     * 根据关联信息查询企业
     * 
     * @param relation 关联信息（格式如：关联企业库QY-001、QY-004等)
     * @return 相关企业信息
     */
    @ApiOperation(value = "根据关联信息查询企业")
    @GetMapping("/getByRelation")
    public ResultData getByRelation(@RequestParam("relation") String relation) {
        if (StringUtils.isEmpty(relation)) {
            return ResultData.build().error("关联信息不能为空");
        }
        
        // 从关联信息中提取企业编号
        String companyCode = companyService.extractCompanyCodeFromRelation(relation);
        if (StringUtils.isEmpty(companyCode)) {
            return ResultData.build().error("未找到有效的企业编号");
        }
        
        CompanyEntity company = companyService.getByCompanyCode(companyCode);
        if (company == null) {
            return ResultData.build().error("未找到对应的企业信息");
        }
        
        return ResultData.build().success(company);
    }
    
    /**
     * 导入企业
     */
    @ApiOperation(value = "导入企业")
    @PostMapping("/import")
    public ResultData importCompanies(HttpServletRequest request, HttpServletResponse response) {
        try {
            MultipartFile file = (MultipartFile) request.getAttribute("file");
            if (file == null) {
                return ResultData.build().error("请选择要导入的Excel文件");
            }
            String result = companyService.importExcel(file);
            return ResultData.build().success(result);
        } catch (Exception e) {
            return ResultData.build().error(e.getMessage());
        }
    }
    
    /**
     * 下载导入模板
     */
    @ApiOperation(value = "下载导入模板")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 重定向到RelationController的模板下载功能
            response.sendRedirect("../relation/importTemplate/company");
        } catch (IOException e) {
            LOG.error("模板下载失败", e);
        }
    }

    /**
     * 根据专家编号查询关联的企业
     */
    @ApiOperation(value = "根据专家编号查询关联的企业")
    @GetMapping("/getByExpert")
    public ResultData getByExpert(@RequestParam("expertCode") String expertCode) {
        if (StringUtils.isEmpty(expertCode)) {
            return ResultData.build().error("专家编号不能为空");
        }
        
        List<CompanyEntity> companies = companyService.getByExpertCode(expertCode);
        return ResultData.build().success(companies);
    }
} 